// pages/pro_detail/pro_detail.js
var app = getApp();

var common = require("../../common/common.js").common;

var WxParse = require("../../wxParse/wxParse.js");

var leader = require("../../common/leader.js").leader;

var colorParse = require("../../common/color.js");

var util = require("../../utils/util.js");

var {$author: $author} = require("../../components/base/authorization.js");

var un = require("../../siteinfo.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        fromType: "normal",
        pagesLength: 1,
        //仅有一页，不显示返回按钮
        showInfoTip: false,
        //授权失败的弹框
        video_show: 0,
        //是否显示视频
        currentSwiper: 0,
        alert1: 0,
        alert: 0,
        close: 1,
        details: [],
        price: "",
        sku: "",
        buy_count: 1,
        sku_info: "",
        cart: [],
        product_id: 0,
        cart_count: 0,
        pid: "",
        is_new: 1,
        //默认是新人商品 走判断 
        goods: [],
        index_msg: [],
        detail: "",
        btn_true: 1,
        leader_id: "",
        warrant: true,
        custom_attributes_show: 0,
        color_header: "",
        color_main: "",
        color_minor: "",
        rich: "",
        details2: "",
        options: "",
        s_leader: [],
        leader_id_share: "",
        myleaderinfo: {},
        goodsId: "",
        isIPX: "",
        on_off_trans_free: 0,
        trans_for_free_barrier: 0,
        flash: 0,
        flash1: 0,
        toastHide: true,
        leaderChange: false,
        //团长切换弹窗显示隐藏，false为隐藏
        currentLeaderInfo: {},
        //当前团长信息
        modalHide: true,
        //提示框显示隐藏，true影藏
        autoplay: true,
        noSale: false,
        tansWay: false,
        current: "tab1",
        componentStyle: {
            navigationTitle: "",
            goBack: true
        },
        process_width: 0,
        tmplIds: [],
        subscribeMessage: true,
        killPoster: false,
        leaderVip: 0,
        benifit: 0,
        vipStatus_deal: 0,
        index_discount: [],
        redPackage: [],
        //红包列表
        redPackage_id: "",
        //上一次领取红包的id
        redPackage_flag: false,
        redPackageChange: false,
        redPackageSmallFlag: false,
        num_count: 0
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        this.setData({
            fromType: options.type || "normal"
        });
        wx.showShareMenu({
            withShareTicket: false,
            menus: [ "shareAppMessage", "shareTimeline" ]
        });
        let pagesLength = getCurrentPages().length;
        var isIPX = app.globalData.isIPX;
        this.setData({
            isIPX: isIPX,
            pagesLength: pagesLength,
            domain: app.globalData.domain.slice(0, -10)
        });
        let that = this;
        //活动商品
                if (options.group_id) {
            that.setData({
                group_id: options.group_id
            });
        }
        //解析分享二维码和分享首页的数据scene
                var scene;
        var s_leader;
        if (options.scene) {
            scene = decodeURIComponent(options.scene);
            s_leader = scene.split(":");
            that.setData({
                options: options,
                s_leader: s_leader,
                s_uid: s_leader[5]
            });
        }
        //解析商品id  从页面点击传 id  二维码为scene的[3]
                let goodsId;
        if (options.id) {
            goodsId = options.id;
        } else {
            goodsId = s_leader[3];
        }
        that.setData({
            goodsId: goodsId
        });
        wx.getSystemInfo({
            success: function(res) {
                let rpx = res.windowWidth / 375;
                that.setData({
                    rpx: rpx
                });
            }
        });
        that.getTmplIds();
        setTimeout(() => {
            that.getBenifit();
        }, 1e3);
        if (app.globalData.user) {
            //如果直接拿到openid
            that.setData({
                openid: app.globalData.user.openid,
                uid: app.globalData.user.uid
            });
            that.requestStart(app.globalData.user.openid);
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                that.setData({
                    openid: res.openid,
                    uid: res.uid
                });
                that.requestStart(res.openid);
            });
        }
        if (options && options.onshare && options.onshare == 1) {
            that.requestStart();
        }
        that.getIndexdiscount(that.data.openid);
        //红包广场
        },
    //红包广场
    getIndexdiscount: function(openid) {
        var that = this;
        var id = that.data.goodsId;
        var params = {};
        if (that.data.group_id) {
            params = {
                id: id,
                group_id: that.data.group_id,
                visit_type: 1
            };
        } else {
            params = {
                id: id,
                visit_type: 1
            };
        }
        common.request({
            endpoint: "product/product_detail",
            method: "post",
            data: params,
            success: res => {
                console.log("23009999999999999999999");
                let aaa = [];
                res.extra.voucher.forEach((item, indx) => {
                    item.redPackageChange = false;
                    aaa.push(item);
                });
                if (that.data.redPackage_id) {
                    aaa.forEach((item, index) => {
                        if (that.data.redPackage_id == item.id) {
                            if (item.receive == 0 || item.stock_num == 0) {
                                item.redPackageChange = true;
                                if (!that.data.redPackageChange) {
                                    that.setData({
                                        index_discount: aaa,
                                        redPackage_flag: false
                                    });
                                } else {
                                    that.setData({
                                        redPackage: aaa,
                                        redPackage_flag: true
                                    });
                                }
                            } else {
                                that.setData({
                                    redPackage: aaa,
                                    redPackage_flag: true
                                });
                            }
                        }
                    });
                } else {
                    that.setData({
                        index_discount: aaa,
                        redPackage_flag: false
                    });
                }
            }
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    getMyInfo: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/myinfo/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                that.setData({
                    info: res.extra
                });
            }
        });
    },
    /**
   * 分销商绑定上下级
   */
    levelShare: function() {
        let that = this;
        common.request({
            endpoint: "Level/level/level-share",
            method: "post",
            data: {
                user_id: that.data.s_uid
            },
            success: res => {
                if (that.data.level_set.success_bind_tip) {
                    wx.showToast({
                        icon: "none",
                        title: that.data.level_set.success_bind_tip
                    });
                } else {
                    wx.showToast({
                        icon: "none",
                        title: "绑定成功"
                    });
                }
            },
            fail(err) {}
        });
    },
    onShow: function() {
        let that = this;
        leader.getMyLeaderInfo(that.data.openid, that.data.s_leader[1]);
        //公用方法团长请求
        },
    goTovipPage: function() {
        let that = this;
        if (that.data.vipStatus == 0) {
            common.getUserInfoNew({
                success() {
                    wx.navigateTo({
                        url: "/memberVip/pages/memberAuthor/memberAuthor?vipStatus=" + that.data.vipStatus
                    });
                }
            });
        } else if (that.data.vipStatus == 1 || that.data.vipStatus == 2 || that.data.vipStatus == 3) {
            wx.navigateTo({
                url: "/memberVip/pages/memberOpen/memberOpen?vipStatus=" + that.data.vipStatus
            });
        } else if (that.data.vipStatus == -1) {
            common.getUserInfoNew({
                success() {
                    wx.navigateTo({
                        url: "/memberVip/pages/memberOpen/memberOpen?vipStatus=" + that.data.vipStatus
                    });
                }
            });
        }
    },
    makeWxapp_img: function(ctx, options) {
        let that = this;
        let name = that.data.title;
        let nameLen = name.length;
        let titleLen = 32.5 + nameLen * 16;
        ctx.drawImage(that.data.domain + "/img/mainPack/share_title.png", (250 - titleLen) * that.data.rpx, 0, (titleLen + 60) * that.data.rpx, 30 * that.data.rpx);
        //图片加载完成   
                if (that.data.wxapp_img) {
            let wxapp_img = that.data.wxapp_img;
            if (wxapp_img.indexOf("https:") < 0) {
                wxapp_img = wxapp_img.replace("http:", "https:");
            }
            wx.getImageInfo({
                src: wxapp_img,
                success: function(res) {
                    ctx.save();
                    ctx.beginPath();
                    //开始绘
                                        ctx.arc((260 - titleLen + 30) * that.data.rpx, 15 * that.data.rpx, 10 * that.data.rpx, 0, Math.PI * 2, false);
                    ctx.clip();
                    ctx.drawImage(res.path, (260 - titleLen + 20) * that.data.rpx, 5 * that.data.rpx, 20 * that.data.rpx, 20 * that.data.rpx);
                    ctx.restore();
                    options.callback();
                },
                fail(res) {
                    options.callback();
                }
            });
        } else {
            options.callback();
        }
    },
    getShareImg2: function() {
        let that = this;
        const ctx = wx.createCanvasContext("shareCanvas");
        ctx.drawImage(that.data.domain + "/img/mainPack//share_bg.png", 0, 0, 300 * that.data.rpx, 240 * that.data.rpx);
        //图片加载完成时draw
                let carousel = that.data.details.carousel_img[0];
        if (carousel.indexOf("https:") < 0) {
            carousel = carousel.replace("http:", "https:");
        }
        wx.getImageInfo({
            src: carousel,
            success: function(res) {
                ctx.drawImage(res.path, 10 * that.data.rpx, 10 * that.data.rpx, 280 * that.data.rpx, 178 * that.data.rpx);
                that.makeWxapp_img(ctx, {
                    callback() {
                        let name = that.data.title;
                        let nameLen = name.length;
                        let titleLen = 32.5 + nameLen * 16;
                        ctx.fillStyle = "#fff";
                        ctx.font = "normal bold 16px sans-serif";
                        ctx.fillText(name, (300 - titleLen + 15) * that.data.rpx, 20 * that.data.rpx);
                        if (that.data.sku_num_display == 1) {
                            ctx.fillStyle = "#fff";
                            ctx.font = "12px YaHei";
                            ctx.fillText("已抢" + that.data.details.sell_number + "件/仅剩" + that.data.details.all_stock_number + "件", 70 * that.data.rpx, 202 * that.data.rpx);
                        }
                        ctx.fillStyle = "#fff";
                        ctx.font = "16px YaHei";
                        ctx.fillText("￥", 70 * that.data.rpx, 230 * that.data.rpx);
                        ctx.fillStyle = "#fff";
                        ctx.font = "25px YaHei";
                        ctx.fillText(that.data.details.before_price, 90 * that.data.rpx, 230 * that.data.rpx);
                        var low_price_width = ctx.measureText(that.data.details.before_price).width;
                        ctx.fillStyle = "#fff";
                        ctx.font = "16px YaHei";
                        ctx.fillText("￥" + that.data.details.low_oprice, (90 + low_price_width + 6) * that.data.rpx, 230 * that.data.rpx);
                        var low_oprice_width = ctx.measureText("￥" + that.data.details.low_oprice).width;
                        ctx.fillStyle = "#fff";
                        ctx.font = "19px YaHei";
                        ctx.fillText("社区", 8 * that.data.rpx, 210 * that.data.rpx);
                        ctx.fillText("团购", 8 * that.data.rpx, 233 * that.data.rpx);
                        ctx.fillStyle = "#fff";
                        ctx.font = "11px YaHei";
                        ctx.fillText("24小时", 255 * that.data.rpx, 220 * that.data.rpx);
                        ctx.fillText("为您服务", 248 * that.data.rpx, 234 * that.data.rpx);
                        ctx.strokeStyle = "#fff";
                        ctx.setLineWidth = 1.5 * that.data.rpx;
                        ctx.moveTo((85 + low_price_width + 6) * that.data.rpx, 225 * that.data.rpx);
                        ctx.lineTo((85 + low_price_width + 6 + low_oprice_width + 2) * that.data.rpx, 225 * that.data.rpx);
                        ctx.stroke();
                        ctx.draw(true, () => {
                            wx.canvasToTempFilePath({
                                canvasId: "shareCanvas",
                                fileType: "png",
                                success: function(res) {
                                    that.setData({
                                        shareCanvasPhoto: res.tempFilePath
                                    });
                                    console.log(res.tempFilePath);
                                },
                                fail: function(res) {},
                                complete: function(res) {
                                    wx.hideLoading();
                                }
                            }, that);
                        });
                    }
                });
            },
            fail(err) {
                console.log(err);
                wx.hideLoading();
            }
        });
    },
    loadImage: function(canvas, src) {
        return new Promise((resolve, reject) => {
            const img = canvas.createImage();
            img.src = src;
            img.onload = (() => {
                resolve(img);
            });
            img.onerror = (e => {
                reject(e);
            });
        });
    },
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        let that = this;
        this.getCart();
        setTimeout(() => {
            if (Object.keys(that.data.myleaderinfo).length != 0) {
                that.data.myleaderinfo.trans_type.forEach((v, i) => {
                    if (v.type == 0) {
                        that.setData({
                            pinkage: v.pinkage
                        });
                    }
                });
            }
        }, 1e3);
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function(res) {
        var that = this;
        this.setData({
            alert1: 0
        });
        var name = that.data.details.name;
        var product_id = that.data.product_id;
        var my_leaderID = that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : "0";
        var imgURL = that.data.imgURL;
        var share_link = that.data.share_link;
        var sharePath;
        if (that.data.group_id) {
            //接龙商品
            sharePath = "/pages/pro_detail/pro_detail?group_id=" + that.data.group_id + "&scene=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id + ":uid:" + that.data.uid);
        } else {
            if (share_link == 1) {
                sharePath = "/pages/shareMiddle/shareMiddle?scene=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id + ":uid:" + that.data.uid);
            } else if (share_link == 0) {
                sharePath = "/pages/pro_detail/pro_detail?scene=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id + ":uid:" + that.data.uid);
            } else if (share_link == 2) {
                sharePath = "/pages/index/index?uid=" + that.data.uid + "&pro_id=" + product_id;
            }
        }
        return {
            title: name,
            imageUrl: that.data.shareCanvasPhoto,
            path: sharePath
        };
    },
    onShareTimeline: function() {
        let that = this;
        var my_leaderID = that.data.myleaderinfo.leader_id;
        var product_id = that.data.product_id;
        return {
            title: that.data.details.name,
            imageUrl: that.data.details.icon,
            // 图片 URL
            query: "onshare=1&scene=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id)
        };
    },
    getBenifit: function() {
        let that = this;
        var my_leaderID = that.data.myleaderinfo.leader_id;
        common.request({
            endpoint: "Leader/leaderpersonal/group_benifit",
            method: "post",
            data: {
                leader_id: my_leaderID
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                if (!res.extra) {
                    that.setData({
                        benifit: 0
                    });
                } else {
                    var code_img = res.extra.code_img;
                    if (!code_img && !res.extra.leader_wx) {
                        that.setData({
                            benifit: 0
                        });
                    } else {
                        that.setData({
                            leaderVipDetail: res.extra,
                            code_img: code_img,
                            benifit: 1
                        });
                    }
                }
            },
            faill(err) {}
        });
    },
    /**
   * 会员福利群显示
   */
    leaderVipShow: function() {
        let that = this;
        that.setData({
            leaderVip: 1
        });
    },
    leaderVipHide: function() {
        let that = this;
        that.setData({
            leaderVip: 0
        });
    },
    leaderVipCopy: function() {
        let that = this;
        wx.setClipboardData({
            data: that.data.leaderVipDetail.leader_wx,
            success(res) {
                wx.getClipboardData({
                    success(res) {
                        wx.showToast({
                            title: "复制成功"
                        });
                    }
                });
            }
        });
    },
    /**
   * 计算所有规格属性
   */
    cartesianProductOf() {
        return Array.prototype.reduce.call(arguments, function(a, b) {
            var ret = [];
            a.forEach(function(a) {
                b.forEach(function(b) {
                    ret.push(a.concat([ b ]));
                });
            });
            return ret;
        }, [ [] ]);
    },
    //*******************************************************
    //
    // 整理合并产品页所有请求 hgj 2019.11.04 
    // 下面为封装的共用方法调用
    //
    //*******************************************************
    //首页弹窗
    getUserInfo: function() {
        common.getUserInfo();
    },
    //团长切换共用方法调用
    chooseButt: function(e) {
        leader.chooseButt(e);
    },
    //页面请求开始
    requestStart: function(openid) {
        let that = this;
        that.getVipStatus().then(() => {
            //产品详情相关信息
            that.getData();
        });
        leader.getMyLeaderInfo(openid, that.data.s_leader[1]);
        //公用方法团长请求
                that.getBase(openid);
        //基础配置
        },
    //会员状态 0未开通  -1过期续费
    getVipStatus: function() {
        let that = this;
        return new Promise((resolve, reject) => {
            common.request({
                endpoint: "vipcard/vip-verify",
                method: "POST",
                data: "",
                success: res => {
                    that.setData({
                        vipStatus: res.extra.vip_card
                    });
                    resolve();
                }
            });
        });
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                if (res.extra.copyright_msg) {
                    var copy = res.extra.copyright_msg;
                    var copyText = [];
                    if (copy.indexOf(",") != -1) {
                        copyText = copy.split(",");
                    } else {
                        copyText[0] = copy;
                    }
                } else {
                    copyText = "";
                }
                that.setData({
                    l_change: res.extra.l_change,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    title: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    phone: res.extra.phone,
                    rp_name: res.extra.rp_name,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    lock_fans: res.extra.lock_fans,
                    leader_address_on: res.extra.leader_address_on,
                    plant_show: res.extra.plant_show,
                    plant_bg: res.extra.plant_bg,
                    share_link: res.extra.share_link,
                    share_type: res.extra.share_type,
                    wxapp_img: res.extra.wxapp_img,
                    sku_display: res.extra.sku_display,
                    vip_card_on: res.extra.vip_card_on,
                    new_member_limit: res.extra.new_member_limit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2,
                    is_basic_pack: res.extra.is_basic_pack,
                    custom_title: res.extra.level_set.custom_title,
                    service_qr_switch: res.extra.service_qr_switch,
                    service_qr: res.extra.service_qr,
                    level_set: res.extra.level_set,
                    sku_num_display: res.extra.sku_num_display,
                    vip_card_show: res.extra.vip_card_show,
                    business_info_display: res.extra.business_info_display,
                    sale_time_show: res.extra.sale_time_show,
                    special_custom_name: res.extra.special_custom_name,
                    pro_detail_shelter: res.extra.pro_detail_shelter,
                    recommend_title: res.extra.recommend_title,
                    num_count: res.extra.cart_total_num
                });
                // 处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                if (that.data.s_uid) {
                    that.levelShare();
                }
            }
        });
    },
    //选择团长 判断权限
    goToChooseLeader(e) {
        if (this.data.leader_change != 1) return;
        $author({
            url: e.currentTarget.dataset.url
        });
    },
    //领取红包
    receiveDiscount: function(e) {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var id = e.detail.id;
        that.setData({
            redPackage_id: id
        });
        $author({
            success() {
                common.request({
                    endpoint: "Voucher/voucher/draw",
                    method: "post",
                    data: {
                        openid: openid,
                        vor_id: id
                    },
                    success: res => {
                        if (that.data.redPackage.length > 0) {
                            that.data.redPackage.forEach((item, index) => {
                                if (id == item.id) {
                                    if (item.receive == 1) {
                                        that.setData({
                                            redPackageChange: true
                                        });
                                    }
                                }
                            });
                        } else {
                            that.data.index_discount.forEach((item, index) => {
                                if (id == item.id) {
                                    if (item.receive == 1) {
                                        that.setData({
                                            redPackageChange: true
                                        });
                                    }
                                }
                            });
                        }
                        that.getIndexdiscount(openid);
                        wx.showToast({
                            title: res.message
                        });
                    }
                });
            }
        });
    },
    showQrService: function() {
        let service_qr = [ this.data.service_qr ];
        wx.previewImage({
            urls: service_qr
        });
    },
    //产品主数据-
    getData: function() {
        var that = this;
        var id = that.data.goodsId;
        var params = {};
        if (that.data.group_id) {
            params = {
                id: id,
                group_id: that.data.group_id,
                visit_type: 1
            };
        } else {
            params = {
                id: id,
                visit_type: 1
            };
        }
        common.request({
            endpoint: "product/product_detail",
            method: "post",
            data: params,
            success: res => {
                let details = res.extra;
                console.log(details.status);
                if (details.status == 0) {
                    wx.showModal({
                        title: "提示",
                        content: "此商品已下架无法购买",
                        success(res) {
                            if (res.confirm) {
                                console.log("用户点击确定");
                                wx.switchTab({
                                    url: "/pages/index/index"
                                });
                            } else if (res.cancel) {
                                wx.switchTab({
                                    url: "/pages/index/index"
                                });
                            }
                        }
                    });
                }
                var vipStatus = that.data.vipStatus;
                var is_vip = (vipStatus == 1 || vipStatus == 2 || vipStatus == 3) && details.is_vip == 1 ? 1 : 0;
                if (details.is_mem_level == 1) {
                    if (is_vip == 1) {
                        details.is_mem_level = Number(details.vip_price) > Number(details.mem_level_price) ? 1 : 0;
                        details.vip_price = Number(details.vip_price) > Number(details.mem_level_price) ? details.mem_level_price : details.vip_price;
                    } else {
                        details.vip_price = details.mem_level_price;
                    }
                }
                let custom_attributes_show = 0;
                for (var i = 0; i < details.custom_attributes.length; i++) {
                    if (details.custom_attributes[i]["show"] == 1) {
                        custom_attributes_show++;
                    }
                }
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = this.getProductBySku(details.sku, sku);
                var arr_sku = [];
                var arr_sku_str = [];
                sku_attribute.map(item => {
                    var arr_sku_item = [];
                    item.attribute_value.forEach((subItem, index) => {
                        arr_sku_item.push(subItem.value);
                    });
                    arr_sku.push(arr_sku_item);
                });
                arr_sku = that.cartesianProductOf(...arr_sku);
                arr_sku.map(item => {
                    arr_sku_str.push(item.join("/"));
                });
                that.setData({
                    arr_sku: arr_sku,
                    arr_sku_str: arr_sku_str
                });
                that.setData({
                    custom_attributes_show: custom_attributes_show,
                    details: details,
                    sku: sku,
                    is_new: details.is_new,
                    product_id: id,
                    sku_info: sku_info,
                    only_express: res.extra.only_express
                });
                if (res.code == 1) {
                    wx.showToast({
                        title: res.message,
                        icon: "none"
                    });
                }
                that.getClassProList();
                //加载完主数据   再请求邻居在买   ---------- 这个接口需要优化
                                that.getDetail();
                //在请求产品的描述                        ----------这个也是
                                console.log(that.data.share_type);
                if (that.data.share_type && that.data.share_type == 1) {
                    console.log("画第2种分享图");
                    that.getShareImg2();
                } else {
                    console.log("画第1种分享图");
                    that.getShareImg1();
                    // 生成产品分享图
                                }
            },
            fail(err) {
                if (err.code == 1) {
                    wx.showModal({
                        title: "提示",
                        content: err.message,
                        confirmText: "返回首页",
                        showCancel: false,
                        success() {
                            wx.reLaunch({
                                url: "/pages/index/index"
                            });
                        }
                    });
                }
            }
        });
    },
    //邻居都在买
    getClassProList: function() {
        var that = this;
        common.request({
            endpoint: "product/class_product",
            method: "post",
            data: {
                pid: that.data.details.cid
            },
            success: res => {
                if (res.extra.sub.length > 0) {
                    var process_width = 0;
                    //推荐模块，下方滚动条
                                        if (res.extra.sub.length < 4) {
                        process_width = 120;
                    } else {
                        process_width = 120 * (3 / res.extra.sub.length);
                    }
                    that.setData({
                        goods: res.extra.sub,
                        process_width: process_width
                    });
                }
            }
        });
    },
    //产品详情富文本 和 邻居都在买产品
    getDetail: function() {
        var that = this;
        var id = that.data.goodsId;
        common.request({
            endpoint: "product/product_detail",
            method: "post",
            data: {
                id: id,
                visit_type: 2
            },
            success: res => {
                let details = res.extra;
                details.detail = details.detail.replace(/\<img/gi, '<img style="width:100%;height:auto" ');
                details.detail = details.detail.replace(/data-lazyload/gi, "src");
                console.log(details.detail);
                details.rich = details.rich.replace(/\<img/gi, '<img style="width:100%;height:auto" ');
                that.setData({
                    detail: WxParse.wxParse("detail", "html", details.detail, that, 0),
                    rich: WxParse.wxParse("rich", "html", details.rich, that, 0)
                });
            }
        });
    },
    previewLeaderImage: function(e) {
        let that = this;
        var sharePosterImgURL = [];
        sharePosterImgURL.push(e.currentTarget.dataset.src);
        if (e.currentTarget.dataset.src) {
            wx.previewImage({
                urls: sharePosterImgURL
            });
        }
    },
    //*******************************************************
    //
    // 整理合并首页所有请求 hgj 2019.11.03 
    // 下面为非页面加载后的直接请求
    // 都是一些点击触发的方法
    // 
    //
    //*******************************************************
    //关闭分享弹窗的和分享
    alert_close2: function() {
        let that = this;
        var alert1 = that.data.alert1;
        if (alert1 == 0) {
            alert1 = 1;
            that.setData({
                alert1: alert1
            });
        } else {
            alert1 = 0;
            that.setData({
                alert1: alert1
            });
        }
        that.setData({
            alert1: alert1
        });
    },
    alert_close4: function() {
        let that = this;
        var alert1 = that.data.alert1;
        if (alert1 == 0) {
            alert1 = 1;
            that.setData({
                alert1: alert1
            });
        } else {
            alert1 = 0;
            that.setData({
                alert1: alert1,
                share_link: 0
            });
        }
    },
    //播放暂停视频
    playVideo() {
        let that = this;
        wx.navigateTo({
            url: `/video/pages/goodsVideo/goodsVideo?id=${that.data.product_id}`
        });
        // var video_show = that.data.video_show;
        // common.request({
        //   endpoint: "video/video_play",
        //   data: {
        //     id: that.data.product_id
        //   },
        //   method: "post",
        //   success(res) {
        //     if (video_show == 1) {
        //       video_show = 0
        //     } else {
        //       video_show = 1
        //     }
        //     that.setData({
        //       videoSrc: res.data,
        //       video_show: video_show
        //     })
        //   },
        //   fail(err) {
        //     that.toastControl("video/video_play请求错误")
        //   }
        // })
        },
    videoErr() {
        this.toastControl("视频格式错误");
    },
    videoEnd() {
        this.setData({
            video_show: 0
        });
    },
    getShareImg1: function() {
        let that = this;
        var details = that.data.details;
        const ctx = wx.createCanvasContext("shareCanvas");
        let carousel = that.data.details.carousel_img[0];
        if (carousel.indexOf("https:") < 0) {
            carousel = carousel.replace("http:", "https:");
        }
        wx.getImageInfo({
            src: carousel,
            success: function(res) {
                console.log("画图成功1");
                ctx.setFillStyle("white");
                ctx.fillRect(0, 0, 600, 500);
                ctx.draw();
                ctx.drawImage(res.path, 55 * that.data.rpx, 0 * that.data.rpx, 190 * that.data.rpx, 190 * that.data.rpx);
                wx.getImageInfo({
                    src: that.data.domain + "/img/pro_share_bg.png",
                    success: function(res) {
                        ctx.drawImage(res.path, 0 * that.data.rpx, 189.5 * that.data.rpx, 300 * that.data.rpx, 50.5 * that.data.rpx);
                        //图片加载完成   
                                                ctx.fillStyle = "#fff";
                        ctx.font = "15px YaHei";
                        ctx.fillText("￥", 14 * that.data.rpx, 213 * that.data.rpx);
                        ctx.font = "22px ArialMT";
                        ctx.fillText(that.data.details.before_price, 27 * that.data.rpx, 213 * that.data.rpx);
                        ctx.font = "10px YaHei";
                        ctx.fillText("￥" + that.data.details.low_oprice, 91.5 * that.data.rpx, 213 * that.data.rpx);
                        var low_oprice_width = ctx.measureText("￥" + that.data.details.low_oprice).width;
                        ctx.strokeStyle = "#fff";
                        ctx.setLineWidth = 2 * that.data.rpx;
                        ctx.moveTo(91.5 * that.data.rpx, 210 * that.data.rpx);
                        ctx.lineTo((91.5 + low_oprice_width) * that.data.rpx, 210 * that.data.rpx);
                        ctx.stroke();
                        ctx.fillStyle = "#fff";
                        ctx.font = "10px YaHei";
                        ctx.fillText("已售" + that.data.details.order_num + "份", 14 * that.data.rpx, 233 * that.data.rpx);
                        ctx.strokeStyle = "#FB7E7E";
                        ctx.setLineWidth = 1 * that.data.rpx;
                        ctx.moveTo(70 * that.data.rpx, 223 * that.data.rpx);
                        ctx.lineTo(70 * that.data.rpx, 233 * that.data.rpx);
                        ctx.stroke();
                        if (that.data.sku_num_display == 1) {
                            ctx.fillStyle = "#fff";
                            ctx.font = "10px YaHei";
                            ctx.fillText("还剩" + that.data.details.all_stock_number + "件", 78 * that.data.rpx, 233 * that.data.rpx);
                        }
                        ctx.fillStyle = "#884A10";
                        ctx.font = "normal bold 14px YaHei";
                        ctx.fillText("立即抢购>", 220 * that.data.rpx, 225 * that.data.rpx);
                        ctx.draw(true, () => {
                            wx.canvasToTempFilePath({
                                canvasId: "shareCanvas",
                                fileType: "png",
                                success: function(res) {
                                    that.setData({
                                        shareCanvasPhoto: res.tempFilePath
                                    });
                                    console.log(res.tempFilePath);
                                },
                                fail: function(res) {},
                                complete: function(res) {}
                            }, that);
                        });
                    }
                });
            }
        });
    },
    makeposter: function() {
        let that = this;
        var my_leaderID = that.data.myleaderinfo.leader_id;
        let leaderinfo_title = that.data.myleaderinfo.title ? that.data.myleaderinfo.title : "-";
        let leaderinfo_name = that.data.myleaderinfo.name ? that.data.myleaderinfo.name : "-";
        let leaderinfo_other = that.data.myleaderinfo.other ? that.data.myleaderinfo.other : "-";
        let leaderinfo_img = that.data.myleaderinfo.other ? that.data.myleaderinfo.img : "/images/default.png";
        const ctx = wx.createCanvasContext("firstCanvas");
        common.request({
            endpoint: "share/poster_read",
            method: "post",
            data: {
                lid: my_leaderID,
                id: that.data.details.id,
                uid: that.data.uid,
                is_supermarket: 0
            },
            success: res => {
                var res = JSON.parse(res);
                let poster_normal = res.data.poster_normal;
                if (poster_normal.indexOf("https") < 0) {
                    poster_normal = poster_normal.replace("http:", "https:");
                }
                let qc = res.data.qc;
                if (poster_normal.indexOf("ngoods_bg") != -1) {
                    if (that.data.style == "1") {
                        //一列大图的缩略图
                        that.setData({
                            ["details.icon"]: that.data.details.carousel_img[0]
                        });
                    }
                    wx.navigateTo({
                        url: "/poster/pages/pro_detail_share/pro_detail_share?id=" + that.data.details.id + "&uid=" + that.data.uid
                    });
                } else {
                    //自定义
                    that.makeposter_define();
                }
            }
        });
    },
    /**
   * x,y-左上角点的坐标；width、height-宽高；radius-圆角；color-绘制颜色；type-绘制类型（'fill'和'stroke'）。
   */
    drawFill: function(x, y, width, height, radius, color, type, ctx) {
        ctx.beginPath();
        ctx.moveTo(x, y + radius);
        ctx.lineTo(x, y + height - radius);
        ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
        ctx.lineTo(x + width - radius, y + height);
        ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
        ctx.lineTo(x + width, y + radius);
        ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
        ctx.lineTo(x + radius, y);
        ctx.quadraticCurveTo(x, y, x, y + radius);
        ctx[type + "Style"] = color || params.color;
        ctx.closePath();
        ctx[type]();
    },
    canvasToImage: function() {
        let that = this;
        setTimeout(() => {
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 375 * that.data.rpx,
                height: 667 * that.data.rpx,
                destWidth: 4 * 375 * that.data.rpx,
                destHeight: 4 * 667 * that.data.rpx,
                canvasId: "firstCanvas",
                fileType: "png",
                quality: 0,
                success: function(res) {
                    let url = [];
                    url.push(res.tempFilePath);
                    wx.previewImage({
                        current: "",
                        // 当前显示图片的http链接
                        urls: url
                    });
                    setTimeout(() => {
                        that.setData({
                            killPoster: false,
                            alert1: 0
                        });
                    }, 1e3);
                },
                fail: function(res) {},
                complete: function(res) {}
            }, that);
        });
    },
    //处理文字多出省略号显示
    dealWords: function(options) {
        options.ctx.setFontSize(options.fontSize);
        //设置字体大小
                options.ctx.font = options.font;
        options.ctx.setFillStyle(options.FillStyle);
        var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);
        //实际总共能分多少行
                var count = allRow >= options.maxLine ? options.maxLine : allRow;
        //实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
                var endPos = 0;
        //当前字符串的截断点
                for (var j = 0; j < count; j++) {
            var nowStr = options.word.slice(endPos);
            //当前剩余的字符串
                        var rowWid = 0;
            //每一行当前宽度    
                        if (options.ctx.measureText(nowStr).width > options.maxWidth) {
                //如果当前的字符串宽度大于最大宽度，然后开始截取
                for (var m = 0; m < nowStr.length; m++) {
                    rowWid += options.ctx.measureText(nowStr[m]).width;
                    //当前字符串总宽度
                                        if (rowWid > options.maxWidth) {
                        if (j === options.maxLine - 1) {
                            //如果是最后一行
                            options.ctx.fillText(nowStr.slice(0, m - 1) + "...", options.x, options.y + (j + 1) * 18);
                            //(j+1)*18这是每一行的高度        
                                                } else {
                            options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 18);
                        }
                        endPos += m;
                        //下次截断点
                                                break;
                    }
                }
            } else {
                //如果当前的字符串宽度小于最大宽度就直接输出
                options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
            }
        }
    },
    makeposter_define: function() {
        let that = this;
        var leaderInfo = that.data.myleaderinfo;
        if (leaderInfo) {
            that.setData({
                alert1: 0
            });
            this.getSharePoster(leaderInfo);
        } else {
            wx.showToast({
                title: "缺少团长信息",
                icon: "none"
            });
        }
    },
    swiperChange: function(e) {
        this.setData({
            currentSwiper: e.detail.current
        });
    },
    close_alert: function(e) {
        this.setData({
            alert: 0
        });
    },
    //转发海报生成
    getSharePoster(leaderInfo) {
        let that = this;
        var details = that.data.details;
        wx.showLoading({
            title: "海报生成中",
            mask: true
        });
        common.request({
            endpoint: "share/poster_normal",
            method: "post",
            data: {
                id: details.id,
                //商品id
                name: leaderInfo.name,
                //团长姓名    
                gname: leaderInfo.other,
                //团名
                address: leaderInfo.title,
                //收货地址
                lid: leaderInfo.leader_id,
                //团长的用户id  
                price: details.low_price,
                original_price: details.low_oprice,
                time_id: "",
                //(秒杀要)
                uid: that.data.uid
            },
            success(res) {
                res = JSON.parse(res);
                var imgURL = res.extra.image ? res.extra.image[0].url : "";
                wx.hideLoading();
                if (res.code == 4) {
                    wx.showToast({
                        title: res.extra
                    });
                } else {
                    var sharePosterImgURL = [];
                    sharePosterImgURL.push(imgURL);
                    wx.previewImage({
                        urls: sharePosterImgURL
                    });
                    that.setData({
                        sharePosterImgURL: imgURL
                    });
                }
            },
            fail(err) {
                console.log(err, "err");
                wx.showToast({
                    title: err.message,
                    icon: "none"
                });
            }
        });
    },
    //提示框
    toastControl(content, time) {
        var that = this;
        that.setData({
            toastContent: content,
            toastHide: false
        });
        //显示提示框
                setTimeout(() => {
            that.setData({
                toastHide: true
            });
        }, !time ? 3e3 : time);
        //定时隐藏提示框,默认3秒后隐藏
        },
    handleChange({detail: detail}) {
        this.setData({
            current: detail.key
        });
    },
    goToUrl(e) {
        let that = this;
        common.getUserInfoNew({
            success() {
                if (that.data.group_id && that.data.details.leader_buy == 1 && that.data.myleaderinfo.iam_leader != 1) {
                    wx.showModal({
                        title: "提示",
                        content: "您不是" + that.data.leaderName + "没有购买权限",
                        showCancel: false,
                        success(res) {}
                    });
                    return false;
                }
                if ((!that.data.myleaderinfo.leader_id || that.data.myleaderinfo.leader_id == -1) && that.data.defaultPro.length) {
                    wx.showModal({
                        title: "提示",
                        content: "您还没有选择" + that.data.leaderName + "，请先选择" + that.data.leaderName + "后再下单",
                        showCancel: false,
                        success(res) {
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: "/pages/nearby_group2/nearby_group2"
                                });
                            }
                        }
                    });
                } else {
                    let pathUrl;
                    if (that.data.group_id) {
                        pathUrl = e.currentTarget.dataset.url + `?group_id=${that.data.group_id}`;
                    } else {
                        pathUrl = e.currentTarget.dataset.url;
                    }
                    wx.navigateTo({
                        url: pathUrl
                    });
                }
            }
        });
    },
    goToUrl1: function(e) {
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    goBack() {
        let that = this;
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        prevPage.setData({
            class_one_id: "",
            class_two_id: ""
        });
        app.globalData.link = "";
        wx.navigateBack({});
        // wx.navigateBack({
        //   delta: 1
        // });
    },
    openMap() {
        let latitude = parseFloat(this.data.latitude);
        let longitude = parseFloat(this.data.longitude);
        wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: this.data.myleaderinfo.title,
            address: this.data.myleaderinfo.other
        });
    },
    onPageScroll(e) {
        return;
    },
    isNewCustomer2(id, sta) {
        let that = this;
        common.request({
            endpoint: "product/new_customer_judge",
            method: "post",
            data: {
                open_id: wx.getStorageSync("user").openid,
                id: id
            },
            success: res => {
                if (res.code == 0) {
                    if (sta == 1) {
                        that.join_goods_current();
                    } else if (sta == 2) {
                        that.buy_current();
                    }
                } else {
                    that.toastControl("此商品只能新用户购买哟", 3e3);
                }
            },
            fail() {
                that.toastControl("此商品只能新用户购买哟", 3e3);
            }
        });
    },
    /** 
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info,
            buy_count: 1
        });
    },
    /** 
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    save_count: function(e) {
        if (this.data.group_id) {
            if (this.data.sku_info.pro_limit == 0) {
                this.setData({
                    buy_count: parseInt(e.detail.value)
                });
            } else {
                if (parseInt(e.detail.value) > this.data.sku_info.pro_limit) {
                    wx.showModal({
                        title: "提示",
                        content: "本商品限购" + this.data.sku_info.pro_limit + "份"
                    });
                    this.setData({
                        buy_count: 1
                    });
                } else {
                    this.setData({
                        buy_count: parseInt(e.detail.value)
                    });
                }
            }
        } else {
            this.setData({
                buy_count: parseInt(e.detail.value)
            });
        }
    },
    blur: function(e) {
        let count = e.detail.value;
        if (count <= 0) {
            count = 1;
        }
        this.setData({
            buy_count: parseInt(count)
        });
    },
    reduce_count: function() {
        let that = this;
        let buy_count = this.data.buy_count;
        var num = buy_count <= parseInt(that.data.details.minimum_num) ? buy_count : parseInt(that.data.details.step_num);
        if (buy_count > 1) {
            buy_count = that.data.details.is_single == 1 ? buy_count - num : buy_count - 1;
        }
        this.setData({
            buy_count: buy_count
        });
    },
    add_count: function(e) {
        let that = this;
        if (that.data.new_member_limit == 1 && that.data.details.is_new == 1) {
            wx.showModal({
                title: "提示",
                content: "新人专享商品只能购买一件,无法加购！",
                showCancel: false
            });
            return false;
        }
        that.add_count_ch(e);
        // if (that.data.subscribeMessage) {
        //   wx.requestSubscribeMessage({
        //     tmplIds: that.data.tmplIds,
        //     success(res) {},
        //     fail(err) {
        //       console.log(err);
        //     }
        //   })
        // }
        },
    add_count_ch: function(e) {
        let that = this;
        let buy_count = this.data.buy_count;
        let restrictions = e.currentTarget.dataset.restrictions;
        if (this.data.group_id) {
            restrictions = this.data.sku_info.pro_limit;
        }
        console.log(that.data.details.is_single);
        if (restrictions == 0) {
            if (buy_count == 0) {
                buy_count = that.data.details.is_single == 1 ? parseInt(buy_count) + parseInt(that.data.details.minimum_num) : buy_count + 1;
            } else {
                buy_count = that.data.details.is_single == 1 ? parseInt(buy_count) + parseInt(that.data.details.step_num) : buy_count + 1;
            }
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + restrictions + "份"
                });
            } else {
                if (buy_count == 0) {
                    buy_count = that.data.details.is_single == 1 ? parseInt(buy_count) + parseInt(that.data.details.minimum_num) : buy_count + 1;
                } else {
                    buy_count = that.data.details.is_single == 1 ? parseInt(buy_count) + parseInt(that.data.details.step_num) : buy_count + 1;
                }
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    isNewJoin: function(id) {
        let that = this;
        var cart = wx.getStorageSync("cart");
        var isCheck = true;
        cart.map(x => {
            if (x.is_new == 1 && x.count >= 1) {
                wx.showModal({
                    title: "提示",
                    content: "新人专享只能购买一件，无法加购！",
                    showCancel: false
                });
                isCheck = false;
            }
        });
        return isCheck;
    },
    join_goods: function() {
        let that = this;
        if (that.data.alert == 0) {
            if (that.data.details.is_single == 1) {
                that.setData({
                    buy_count: that.data.details.minimum_num
                });
            } else {
                that.setData({
                    buy_count: 1
                });
            }
        }
        let user = wx.getStorageSync("user");
        if (!user.nickname) {
            common.getUserInfoNew({
                success(res) {
                    //不是会员
                    if (that.data.vipStatus <= 0) {
                        //付费会员才可以购买
                        if (that.data.details.only_vip == 1) {
                            wx.showModal({
                                title: "提示",
                                content: "该商品仅限会员购买，请先成为会员",
                                confirmText: "去升级",
                                success(res) {
                                    if (res.confirm) {
                                        wx.redirectTo({
                                            url: "/memberVip/pages/memberAuthor/memberAuthor"
                                        });
                                        return;
                                    } else {
                                        return;
                                    }
                                }
                            });
                            return;
                        }
                    }
                    if (that.data.new_member_limit == 1 && that.data.details.is_new == 1) {
                        if (!that.isNewJoin(id)) {
                            return false;
                        }
                    }
                    var id = that.data.goodsId;
                    if (that.data.is_new == 1) {
                        that.isNewCustomer2(id, 1);
                    } else {
                        that.join_goods_current();
                    }
                }
            });
            return;
        }
        //不是会员
                if (that.data.vipStatus <= 0) {
            //付费会员才可以购买
            if (that.data.details.only_vip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        if (that.data.new_member_limit == 1 && that.data.details.is_new == 1) {
            if (!that.isNewJoin(id)) {
                return false;
            }
        }
        var id = that.data.goodsId;
        if (that.data.is_new == 1) {
            that.isNewCustomer2(id, 1);
        } else {
            that.join_goods_current();
        }
    },
    buy: function(event) {
        let that = this;
        if (event.target.dataset.form == 1 && that.data.fromType != "dragon") {
            if (that.data.details.is_single == 1) {
                that.setData({
                    buy_count: that.data.details.minimum_num
                });
            } else {
                that.setData({
                    buy_count: 1
                });
            }
        }
        //不是会员
                if (that.data.vipStatus <= 0) {
            //付费会员才可以购买
            if (that.data.details.only_vip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        if (that.data.group_id && that.data.details.leader_buy == 1 && that.data.myleaderinfo.iam_leader != 1) {
            wx.showModal({
                title: "提示",
                content: "您不是" + that.data.leaderName + "没有购买权限",
                showCancel: false,
                success(res) {}
            });
            return false;
        }
        var id = that.data.goodsId;
        common.getUserInfoNew({
            success() {
                if (that.data.is_new == 1) {
                    that.isNewCustomer2(id, 2);
                } else {
                    that.buy_current();
                }
            }
        });
    },
    join_goods_current: function() {
        var that = this;
        var alert = that.data.alert;
        if (alert == 0) {
            this.setData({
                alert: 1,
                btn_true: 1
            });
        } else {
            that.join_goods_current_ch();
            // if (that.data.subscribeMessage) {
            //   wx.requestSubscribeMessage({
            //     tmplIds: that.data.tmplIds,
            //     success(res) {
            //     },
            //     fail(err) {
            //       console.log(err);
            //     }
            //   })
            // }
                }
    },
    join_goods_current_ch: function() {
        var that = this;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        if (sku_info.stock_number >= buy_count) {
            that.cartRequest(that.data.sku_info.item_id, "add", 2);
        } else {
            wx.showToast({
                title: "加入购物车失败",
                icon: "none"
            });
        }
    },
    cartRequest(sku, type, id, single) {
        let that = this;
        let num = 0;
        if (single == 1) {
            num = type == "add" ? 1 : -1;
        } else {
            num = that.data.buy_count;
        }
        common.request({
            endpoint: "Order/cart/add",
            method: "post",
            data: {
                leader_id: that.data.myleaderinfo.leader_id != -1 ? that.data.myleaderinfo.leader_id : 0,
                sku_id: sku,
                business_id: 0,
                num: num,
                flag: that.data.comeon == 2 ? 1 : 0,
                type: 0
            },
            success: res => {
                let shopcartSuccess = "加入购物车成功";
                if (that.data.langIndex == 1) {
                    shopcartSuccess = "مۇۋەپپەقىيەتلىك ھالدا ھارۋىغا قوشۇڭ";
                }
                wx.showToast({
                    title: shopcartSuccess,
                    icon: "success",
                    duration: 2e3
                });
                that.setData({
                    alert: 0
                });
                that.getBase();
                if (that.data.subscribeMessage) {
                    wx.requestSubscribeMessage({
                        tmplIds: that.data.tmplIds,
                        success(res) {},
                        fail(err) {
                            console.log(err);
                        },
                        complete() {}
                    });
                }
            },
            fail: err => {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    },
    buy_current: function() {
        var that = this;
        var alert = that.data.alert;
        if (alert == 0) {
            this.setData({
                alert: 1,
                btn_true: 2
            });
        } else {
            if (that.data.subscribeMessage) {
                wx.requestSubscribeMessage({
                    tmplIds: that.data.tmplIds,
                    success(res) {},
                    fail(err) {},
                    complete() {
                        that.buy_current_ch();
                    }
                });
            } else {
                that.buy_current_ch();
            }
        }
    },
    buy_current_ch: function() {
        let that = this;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var id = that.data.goodsId;
        var sku_id = sku_info.item_id;
        var credit_sent = sku_info.credit_sent;
        let sku_item = sku_info.item_id + "," + buy_count + "," + credit_sent + "," + details.only_express;
        if (sku_info.stock_number >= buy_count) {
            let pathUrl;
            if (that.data.group_id) {
                pathUrl = "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 0 + "&group_id=" + that.data.group_id;
            } else {
                pathUrl = "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 0;
            }
            wx.navigateTo({
                url: pathUrl
            });
        } else {
            wx.showToast({
                title: "库存不足",
                icon: "none"
            });
        }
    },
    getCart: function() {
        var that = this;
        let goods = wx.getStorageSync("cart");
        let invalid = wx.getStorageSync("invalid") || [];
        let item_idBox = [];
        let items = [];
        let items2 = [];
        for (var i = 0; i < goods.length; i++) {
            item_idBox.push(goods[i].id);
        }
        for (var i = 0; i < invalid.length; i++) {
            goods.push(invalid[i]);
            item_idBox.push(invalid[i].id);
        }
        var params = {
            data: item_idBox
        };
        if (that.data.group_id) {
            params["group_id"] = that.data.group_id;
        }
        common.request({
            endpoint: "product/cart_num",
            method: "post",
            data: params,
            success: res => {
                var stock;
                var defaultPro = res.extra.default;
                var express = res.extra.express;
                that.setData({
                    defaultPro: defaultPro,
                    express: express
                });
                //处理数据
                                if (defaultPro.length > 0) {
                    defaultPro.forEach((item, index) => {
                        item.proType = 0;
                    });
                }
                if (express.length > 0) {
                    express.forEach((item, index) => {
                        item.proType = 1;
                    });
                }
                stock = defaultPro.concat(express);
                for (var i = 0; i < stock.length; i++) {
                    if (stock[i].status == 1) {
                        if (stock[i].stock_number > 0) {
                            goods[i].stock_number = stock[i].stock_number;
                            items.push(goods[i]);
                        } else {
                            items2.push(goods[i]);
                        }
                    } else {
                        goods[i].status = 0;
                        items2.push(goods[i]);
                    }
                }
                for (var j = 0; j < items.length; j++) {
                    items[j]["select"] = 0;
                }
                let cart_count = 0;
                for (var i = 0; i < items.length; i++) {
                    if (that.data.group_id) {
                        if (items[i].group_id) {
                            cart_count += items[i]["count"];
                        }
                    } else {
                        cart_count += items[i]["count"];
                    }
                }
                wx.setStorage({
                    key: "cart_count",
                    data: cart_count
                });
                wx.setStorage({
                    key: "cart",
                    data: items
                });
                wx.setStorage({
                    key: "invalid",
                    data: items2
                });
                this.setData({
                    cart_count: cart_count
                });
            }
        });
    },
    //一键回到顶部
    goTop: function(e) {
        wx.pageScrollTo({
            scrollTop: 0
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "21" || v.type == "22" || v.type == "23") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    }
});